import IPy
import subprocess
import re


def check_ip(genmask):
    compile_ip = re.compile(
        '^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(0)/(\d|[1-2]\d|3[0-2])$')
    if compile_ip.match(genmask):
        return True
    else:
        return False

with open("ip.txt","w+") as fp:

    while 1:
                genmask = input("please input network segment you want to detect or exit \n")
                if(genmask == 'exit'):
                        break
                else:
                        try:
                                if(check_ip(genmask) is False):
                                        raise ValueError("输入错误")
                        except ValueError:
                                print("输入不合规，请重新输入")
                                continue
                        else:

                                for i in IPy.IP(genmask):
                                        ips = subprocess.call(f"ping {i} -c 1 -w 0.1 -i 0.1",shell="True")
                                        if(ips == 0):
                                                fp.write(f"{i}已经被使用\n")
                                        else:
                                                fp.write(f"{i}未被使用\n")
                                        fp.flush()
                                break


